# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
import enhancedModel as em
import models.role as rm

#from rola import lista_rol

class UserModel( em.EnhancedModel ):
    __prefix__ = 'User'
    account = db.UserProperty(required=True) # google account corresponding to user

    role = db.StringProperty(required=True) # to be changed

    contactData = db.StringProperty(multiline=True)

    def linkTo( self, text = None, action = 'show1', archival=False, umode='-1', link=None ):
        
        defaultText = {"show1" : "(Show)",
                       "showAll" : "(Show all)",
                       "showForUser" : "(Show user's shipping orders)",
                       "edit" : "[Edit]",
                       "delete" : "[Delete]",
                       "new": "(New)"
                       }
        
        linkFunction = {"show1" : "showLink",
                       "showAll" : "showAllLink",
                       "showForUser" : "showForUserLink",
                       "edit" : "editLink",
                       "delete" : "deleteLink",
                       "new" : "newLink"
                       }
        
        if (not text) and (action in defaultText):
            text = defaultText[action]
        
        if not link:
            link = eval('self.'+linkFunction[action]+'()')
            # oczekujemy, że przy braku linka akcja będzie mieć przypisaną funkcję generującą link
        
        if not text:
            raise Exception("No text specified")

        options = ""
        if archival:
            options += "archival=True&"
        
        if action == 'showForUser':
            options += "uid=%d&umode=%d&" % (self.ident, int(umode))
                
        if options:
            options = "?" + options    
            
        return '''<a href="%s%s">%s</a>''' % ( link, options, text )

    def editLink(self):
        return ("/user/edit/id/%d" % self.ident)

    def deleteLink(self):
        return ("/user/delete/id/%d" % self.ident)

    def showLink(self):
        return ("/user/show1/id/%d" % self.ident)

    def showAllLink(self):
        return ("/user/showAll")

    def showForUserLink (self):
        return ("/so/showAll")
        
    def newLink(self):
        return ("/user/new")
    
    @staticmethod
    def findOrCreate(accountname):
        # tries to find existing user with exact account name in datastore
        # if not found, creates new with no privileges
        # then returns appropriate reference
        # TOCONSIDER - perhaps it would be better to return id instead of ref?
        existing = UserModel.all().filter('account =', users.User(accountname)).filter('archival = ', False).get()
        if existing == None:
          new = UserModel(  role = 'pedestrian',
                      account = users.User(accountname))
          new.put()
          return new
        else:
          return existing

    @staticmethod
    def currentHasPermission(permission):
        if users.get_current_user():
          user = UserModel.findOrCreate(users.get_current_user().email())
          # Gives 'admin' role for admin users
          if users.is_current_user_admin():
              user.role = 'admin'
              user.put()
          return rm.roles[user.role].hasPermission(permission)
        else: 
          return False

    @staticmethod
    def userRole():
        if users.get_current_user():
            user = UserModel.findOrCreate(users.get_current_user().email())
            return user.role
        else:
            return None

    @staticmethod
    def userAcc():
        if users.get_current_user():
            user = UserModel.findOrCreate(users.get_current_user().email())
            return user.account
        else:
            return None

    @staticmethod
    def userId():
        if users.get_current_user():
            user = UserModel.findOrCreate(users.get_current_user().email())
            return user.ident
        else:
            return None

    @staticmethod
    def userContact():
        if users.get_current_user():
            user = UserModel.findOrCreate(users.get_current_user().email())
            return user.contactData
        else:
            return None

    def hasPermission(self, permission):
      return rm.roles[self.role].hasPermission(permission)
